import 'package:flutter/material.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:flutter_base/config/app_config.dart';
import 'package:flutter_base/utils/log/utils_log.dart';

import 'api.dart';

bool get isNoNetWork => HttpConnectionCheck.currentNetState == InternetStatus.disconnected;

/// 检查网络状态做无网络处理
class HttpConnectionCheck {
  static InternetConnection? internetConnection;
  static InternetStatus? currentNetState; //当前网络状态
  static Map<String, ValueChanged<InternetStatus>> internetConnectionChangeListenMap = {}; //需要监听网络的列表

  static void addInternetConnectionChangeListen(String key, ValueChanged<InternetStatus> callback) {
    internetConnectionChangeListenMap[key] = callback;
  }

  static void removeInternetConnectionChangeListen(String key) {
    // 防止遍历时减元素
    Future.delayed(const Duration(seconds: 2), () => internetConnectionChangeListenMap.remove(key));
  }

  static Future checkNetWork({bool listen = true}) async {
    internetConnection ??= InternetConnection.createInstance(
      customCheckOptions: [
        InternetCheckOption(uri: Uri.parse(AppConfig.baseUrl + API.heartbeat)),
      ],
    );
    if (internetConnection != null) {
      var status = await internetConnection!.internetStatus;
      _checkListMap(status);
    }
    if (listen) {
      _listen();
    }
  }

  static void _listen() {
    internetConnection?.onStatusChange.listen((InternetStatus status) {
      _checkListMap(status);
    });
  }

  static void _checkListMap(InternetStatus status) {
    try {
      if (currentNetState != null && currentNetState != status && internetConnectionChangeListenMap.isNotEmpty && internetConnectionChangeListenMap.values.isNotEmpty) {
        for (ValueChanged<InternetStatus> v in internetConnectionChangeListenMap.values) {
          v.call(status);
        }
      }
    } catch (e) {
      clog("[当前网络状态] error ===> $e");
    } finally {
      currentNetState = status;
    }
    clog("[当前网络状态]===> $currentNetState");
  }
}
